package mc.support.web.action;

import mc.support.web.WebConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Created with IntelliJ IDEA. <br/>
 * User: francis    <br/>
 * Date: 13-11-5    <br/>
 * Time: 15:02  <br/>
 */
public class ActionLoadListener implements ServletContextListener, WebConstants {

    private static Logger log = LoggerFactory.getLogger( ActionLoadListener.class );

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        final ServletContext servletContext = sce.getServletContext();
        final WebApplicationContext springContext = WebApplicationContextUtils
                .getWebApplicationContext( servletContext );

        servletContext.setAttribute(ACTION_CONTAINER, new ActionContainer() {
            @Override
            public Object getAction(String name) {
                Object action = null;
                try {
                    action = springContext.getBean( name );
                } catch (BeansException e) {
                    log.error( "can't find action named: " + name );
                }

                return action;
            }
        } );
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    
    }

}
